--
-- Author: ping.wang
-- Date: 2018-09-04 17:21:47
--
-- ElevatePeerageView
--
local ElevatePeerageRender = import( ".renders.ElevatePeerageRender" )
local table_insert = table.insert
local fileName = string.getModeName(...)
local string_split = string.split
local IconRender = require("app.widget.renders.IconRender")
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.NewGuildElevateNode

function ClassRef:init()
    self._haveClickConfer = false --是否按下过授予按钮

    self._ui.Button_close:addClickEventListener(function()
        self._ui.Image_seal:setVisible(self._haveClickConfer)
        self:closeView(false)
    end)
    self._tlt = self._ui["Panel/tlt"]
    self._curSelectedName = self._ui["Panel/Panel_bom/name"] --当前选中的爵位名
    self._elevateNumText = self._ui["Panel/Panel_bom/num"] --已授予XX/XX

    local coinConf = GD:getCoinConfig( Enums.PropType.roseGold )
    local iconPath = GD:getImagePath(Res.coinIconPath,coinConf.bigicon)
    self._ui["Panel/Panel_bom/Panel_reward/gold"]:loadTexture(iconPath)
    self._dayAwardText = self._ui["Panel/Panel_bom/Panel_reward/num"] --每日奖励XXX
    self._curSelectedTitleId = 0


    --所有可以授予的官职 一共7个
    self._allRender = {}
    for i = 1, 7 do
        local tmpRender = ElevatePeerageRender.create(self._ui["Panel_list/node_"..i])
        table_insert(self._allRender,tmpRender)
        tmpRender:onBtnClick(handler(self,self.clickTitle))
    end


    --解锁奖励icon
    self._allAwardIcons = {}
    for i = 1, 4 do
        table_insert(self._allAwardIcons,IconRender.create(self._ui["Panel/Panel_bom/icon_"..i]))
    end

    --todo 解锁相关待定
    self._allTitleIds = {}
    local allPeerages = GD:queryElevatePeerages()
    for _,v in ipairs(allPeerages) do
        if tonumber(v.ID) >= 2000 then
            table_insert(self._allTitleIds,tonumber(v.ID))
        end
    end
    self._grantPanel = self._ui.Panel_grant
    self._grantPanel:addTouchEventListener(function( sender, eventType )
        if eventType == ccui.TouchEventType.ended then
            self:grantPlayer()
        end
    end)

    self._revokePanel = self._ui.Panel_revoke
    self._revokePanel:addTouchEventListener(function( sender, eventType )
        if eventType == ccui.TouchEventType.ended then
            self:revokePlayer()
        end
    end)

    if self._timeline then
        self._grantAniInfo = self._timeline:getAnimationInfo("animation")
        self._timeline:gotoFrameAndPause( self._grantAniInfo.startIndex )
    end
end


function ClassRef:setData(playerInfo, guildInfo)
    self._playerInfo = playerInfo
    self._guildInfo = guildInfo
    self._conferTitles = {}
    local maxActivePeerageId = self._guildInfo:getMaxActiveTerritoryId()
    if maxActivePeerageId > 0 then
        local temp = GD:getConferTitlesById(maxActivePeerageId)
        if temp then
            local tempStr = string_split(temp, "|")
            for k,v in ipairs(tempStr) do
                local conferTitle = string_split( v, ":" )
                self._conferTitles[tonumber(conferTitle[1])] = tonumber(conferTitle[2])
            end

        end
    end
    self:refreshView()
end

function ClassRef:refreshView()
    if not self._playerInfo or not self._guildInfo then
        return
    end

    self._tlt:setString(string.format(L("peerage1"),self._playerInfo:getMemberName()) )
    --获取所有7个官职信息
    local titleId = 0
    local selectedIdx = 1
    local maxConferNumId = 1
    for i = 1,#self._allTitleIds do
        titleId = self._allTitleIds[i]
        local titleInfo = GD:queryPeerageById(titleId)
        --获取我现在能授予多少 以及已经授予了多少
        local haveConferNum = self._guildInfo:getConferTitle(titleId)
        local canConferNum = self._conferTitles[titleId] or 0
        if canConferNum > 0 then
            maxConferNumId = i
        end

        self._allRender[i]:setData({titleInfo,haveConferNum,canConferNum})
        if self._curSelectedTitleId == 0 then
            --代表是首次打开
            if self._playerInfo:getTitleId() == titleId then
                selectedIdx = i
            end
        else
            if self._curSelectedTitleId == titleId then
                selectedIdx = i
            end
        end
    end

    if self._curSelectedTitleId == 0 and self._playerInfo:getTitleId() == 0 then
        selectedIdx = maxConferNumId
    end

    --默认选中
    self:chooseTitle(self._allRender[selectedIdx]:getData())
end


--data[1] = titleInfo data[2] = haveConferNum data[3] = canConferNum
function ClassRef:chooseTitle(titleData)
    local titleInfo = titleData[1]
    local titleId = tonumber(titleInfo.ID)

    self._curSelectedTitleId = titleId
    local playerTitleId = self._playerInfo:getTitleId()
    for k,v in ipairs(self._allRender) do
        local info = v:getData()[1]
        if tonumber(info.ID) ~= titleId then
            v:setSelected(false, playerTitleId)
        else
            v:setSelected(true, playerTitleId)
        end
    end
    self._curSelectedName:setString(L(titleInfo.name))

    self._elevateNumText:setString(string.format(L("peerage2"),titleData[2],titleData[3]))
    local awardNum = string_split(titleInfo.roseGold,"|")[3]
    self._dayAwardText:setString(string.format(L("peerage3"),awardNum))

    if playerTitleId == titleId then
        self._grantPanel:setVisible(false)
        self._revokePanel:setVisible(true)
    else
        self._grantPanel:setVisible(true)
        self._revokePanel:setVisible(false)

        if titleData[2] >= titleData[3] then
            self._grantPanel:setVisible(false)
        end

    end

    --刷新奖励的道具icon
    local awardDatas = string_split(UD:parseClassText(titleInfo.rewardShow),";")
    for i = 1, 4 do
        if i <= #awardDatas then
            local awardInfo = string_split(awardDatas[i],"|")

            self._allAwardIcons[i]:setVisible(true)
            self._allAwardIcons[i]:setTipEnable(true)
            self._allAwardIcons[i]:setData(
                UD:parseLootToBagItem({type = tonumber(awardInfo[1]), id = tonumber(awardInfo[2]), num = tonumber(awardInfo[3])}))
        else
            self._allAwardIcons[i]:setVisible(false)
        end

    end


    if self._grantAniInfo then
        self._timeline:gotoFrameAndPause( self._grantAniInfo.startIndex )
    end

end

function ClassRef:grantPlayer()
    if self._playerInfo then
        local confirmDialog = display.newConfirmDialog(string.format(L("peerage5"),self._playerInfo:getMemberName()),
        function()
            --准备向服务器发送授予消息
            --对方的职位不能比你高 授予的职位也不能比你高
            local guildModel = app:getInst("NewguildModel")
            local myMemberInfo = guildModel:getMyGuildMemberInfo()
            if myMemberInfo:isGuildLeader() or (myMemberInfo:getTitleId() > self._playerInfo:getTitleId()) then

                if myMemberInfo:isGuildLeader() or (myMemberInfo:getTitleId() > self._curSelectedTitleId) then
                    executeFunc(self._onOperate, "grandTitle", {self._playerInfo:getMemberId(), self._curSelectedTitleId})
                else
                    display.pushToast(L("GuildPeerageLimit2"))
                end

            else
                display.pushToast(L("GuildPeerageLimit1"))
            end
        end)
        confirmDialog:setTitle(L("peerage4"))
        UIHandler:addPopDialog( confirmDialog )
    end
end

function ClassRef:revokePlayer()
    if self._playerInfo then
        local confirmDialog = display.newConfirmDialog(string.format(L("peerage7"),self._playerInfo:getMemberName()),
            function()
                --准备向服务器发送撤销消息
                local guildModel = app:getInst("NewguildModel")
                local myMemberInfo = guildModel:getMyGuildMemberInfo()
                if myMemberInfo:isGuildLeader() or (myMemberInfo:getTitleId() > self._playerInfo:getTitleId()) then
                    executeFunc(self._onOperate, "revokeTitle", self._playerInfo:getMemberId())
                else
                    display.pushToast(L("GuildPeerageLimit1"))
                end
            end)
        confirmDialog:setTitle(L("peerage6"))
        UIHandler:addPopDialog( confirmDialog )
    end
end

function ClassRef:playGrantAni(titleId)
    self:playAction("animation", false)
    self._grantPanel:setVisible(false)
    self._revokePanel:setVisible(false)
    self._haveClickConfer = true

    for i = 1,#self._allTitleIds do
        if self._allTitleIds[i] == titleId then
            self._allRender[i]:playAni()
            break
        end
    end
end

function ClassRef:clickTitle(titleData)
    self._haveClickConfer = false
    self:chooseTitle(titleData)
end

return ClassRef
